#!/user/bin/python
# _*_ coding: UTF-8 _*_
# Filename: Xiaomi.py
# !/user/bin/python
# _*_ coding: UTF-8 _*_
# Filename: Huawei.py
import time
import pymongo
from selenium import webdriver

client = pymongo.MongoClient('mongodb://localhost:27017')
mydb = client["jdmpresystem"]
product = mydb['Authorproducts']

driver = webdriver.Chrome()
# 修改浏览器部分属性，绕过检测。
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    "source": """Object.defineProperty(navigator,'webdriver',{get:()=> false})"""
})
driver.get('https://www.mi.com/')
driver.implicitly_wait(10)  # 设置浏览器的等待（耗时） 智能化等待 加载完就不会等待
driver.maximize_window()


def drop_down():
    for x in range(1, 10, 2):
        j = x / 9
        js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
        driver.execute_script(js)
        time.sleep(0.5)


driver.find_element_by_css_selector('#search').send_keys('手机')
driver.find_element_by_xpath('//*[@id="J_submitBtn"]/input').click()

time.sleep(3)
for i in range(0, 3):
    drop_down()
    lis = driver.find_elements_by_xpath('//*[@id="app"]/div[2]/div/div/div[2]/div[3]/div/div[2]/div[1]/div')
    for li in lis:
        skuname = li.find_element_by_xpath('a/h2').text
        price = li.find_element_by_class_name('price').find_element_by_xpath('span').text
        price = int(price.split('元')[0])
        comment = -1
        url = li.find_element_by_xpath('a').get_attribute('href')
        img = li.find_element_by_xpath('a/div[1]/img').get_attribute('src')
        phone = {
            'brand':'小米（MI）',
            'price': price,
            'comment': comment,
            'url': url,
            'skuname': skuname,
            'img': img,
            'logourl':'http://localhost:8002/ShopLogo/xm.png'
        }
        x = product.insert_one(phone)
        print(x)
    if i == 2:
        break
    else:
        # app > div.mi-search.page-main > div > div > div.container-main > div.search-result > div > div.goods-list-box > div.mi-pagenav > a.numbers.last
        #app > div.mi-search.page-main > div > div > div.container-main > div.search-result > div > div.goods-list-box > div.mi-pagenav > a.numbers.last
        driver.find_element_by_css_selector('#app > div.mi-search.page-main > div > div > div.container-main > div.search-result > div > div.goods-list-box > div.mi-pagenav > a.numbers.last').click()
